/* 
 * Author: Alexander Rauser, arauser.org
 * Date: August 2008
 * Copyright: 2008
 * Licensed under Creative Commons Attribution 3.0 Unported
 */
 
package org.arauser.uploader.view
{
	import flash.desktop.*;
	import flash.events.*;
	import flash.filesystem.File;
	import flash.net.URLRequest;
	import flash.net.URLRequestMethod;
	
	import org.arauser.uploader.ApplicationFacade;
	import org.arauser.uploader.model.SettingsProxy;
	import org.arauser.uploader.view.components.UploadItem;
	import org.puremvc.as3.interfaces.*;
	import org.puremvc.as3.patterns.facade.*;
	import org.puremvc.as3.patterns.mediator.*;
	
	
	public class UploadItemMediator extends Mediator implements IMediator
	{
		public static const NAME:String = 'UploadItemMediator';
 		
 		private var fileURL:String;
 		private var file:File;
		
		/**
		 * Takes the component, the file to upload and a unique name
		 * We will create multiple Mediators, one for each component.
		 * This is important as otherwise i.e. the onRemoveItem method would not know
		 * wich item to remove, therefore remove the last one in the list.
		 */
		public function UploadItemMediator(viewComponent:UploadItem, f:File, id:String=NAME) {
            
            file = f;
            
            super( id, viewComponent );
           
			uploadItem.addEventListener("REMOVE", onRemoveItem);
            uploadItem.addEventListener("COPY", onCopyLink);
            uploadItem.addEventListener("CANCEL", onCancelLink);
            
            // We start uploading immediately
            upload();
        }
        
        public function upload():void
        {
        	// Listen to the file upload events
        	file.addEventListener( DataEvent.UPLOAD_COMPLETE_DATA, uploadCompleteDataHandler );
			file.addEventListener( IOErrorEvent.IO_ERROR, ioErrorHandler );
			
			// Get the proxy and load the settings, the proxy should be refactored to only load settings once in the app.
			var proxy:SettingsProxy = SettingsProxy(ApplicationFacade.getInstance().retrieveProxy(SettingsProxy.NAME));
            
            // Create the request and start the upload
			var uploadURL:URLRequest = new URLRequest();
            uploadURL.url = proxy.loadSetting("uploadURL");
            uploadURL.method = URLRequestMethod.POST;
            
			file.upload(uploadURL);
			
			// Update the view
			uploadItem.bar.source = file;
			uploadItem.lblName.text = file.name;
        }
        
        /**
        * Triggered once the upload has finished and updates the view.
        */
        private function uploadCompleteDataHandler(event:DataEvent):void {
            uploadItem.bar.visible = false;
            uploadItem.btnCancel.visible = false;
            fileURL = event.data;
            uploadItem.completeState.visible = true;
        }
		/**
		 * Handler for upload errors
		 */
    	private function ioErrorHandler(event:Event):void
    	{
    		uploadItem.lblName.text = "Error uploading + " + event;
    	}
        
        /**
        * Removes the view and the mediator
        */
        private function onRemoveItem(event:Event):void
        {
        	uploadItem.parent.removeChild(uploadItem);

        	facade.removeMediator(this.mediatorName);
        	
        }
        
        /**
        * Copies the link returned from the server after the upload was successful to the clipboard
        */
        private function onCopyLink(event:Event):void
        {
        	Clipboard.generalClipboard.setData(ClipboardFormats.TEXT_FORMAT, fileURL);
        }
        
        /**
        * Cancel the upload
        */
        private function onCancelLink(event:Event):void
        {
        	file.cancel();
        	uploadItem.parent.removeChild(uploadItem);
        	facade.removeMediator(this.mediatorName);	
        }

        /**
        * Cast the viewComponent to its actual type. 
        */
		protected function get uploadItem() : UploadItem {
			return viewComponent as UploadItem;
		}
	}
}